import { readFile } from 'fs/promises'
import { join } from 'path'
import { existsSync } from 'fs'

export default eventHandler(async (event) => {
  const filename = getRouterParam(event, 'filename')
  if (!filename) {
    throw createError({ statusCode: 400, statusMessage: 'FILENAME_REQUIRED' })
  }

  // 验证文件名格式（防止路径遍历攻击）
  if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
    throw createError({ statusCode: 400, statusMessage: 'INVALID_FILENAME' })
  }

  const filepath = join(process.cwd(), 'public', 'uploads', filename)

  // 检查文件是否存在
  if (!existsSync(filepath)) {
    throw createError({ statusCode: 404, statusMessage: 'FILE_NOT_FOUND' })
  }

  // 读取文件
  const fileBuffer = await readFile(filepath)

  // 根据文件扩展名设置 Content-Type
  const ext = filename.split('.').pop()?.toLowerCase()
  const contentTypeMap: Record<string, string> = {
    jpg: 'image/jpeg',
    jpeg: 'image/jpeg',
    png: 'image/png',
    gif: 'image/gif',
    webp: 'image/webp'
  }
  const contentType = contentTypeMap[ext || ''] || 'application/octet-stream'

  // 返回文件
  setHeader(event, 'Content-Type', contentType)
  setHeader(event, 'Cache-Control', 'public, max-age=31536000') // 缓存1年
  return fileBuffer
})

